package com.onlyforfun.exchange;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.actionbarsherlock.widget.ShareActionProvider;
import com.actionbarsherlock.widget.ShareActionProvider.OnShareTargetSelectedListener;
import com.androidquery.service.MarketService;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.mobeta.android.dslv.DragSortListView;
import com.onlyforfun.exchange.dao.BocExchangeDao;
import com.onlyforfun.exchange.dao.ExchangeDao;
import com.onlyforfun.exchange.dao.IcbcExchangeDao;
import com.onlyforfun.exchange.dao.SortKeeper;
import com.onlyforfun.exchange.domain.TimePrice;
import com.onlyforfun.exchange.listner.AdlistenerTracker;
import com.onlyforfun.exchange.util.CurrencyConverter;
import com.onlyforfun.exchange.util.EmptyViewUtils;
import com.onlyforfun.exchange.util.NetWorkUtil;
import com.onlyforfun.exchange.view.CurrentPriceArrayAdapter;

public class CurrentPriceActivity extends AbstractFragmentActivity implements ActionBar.OnNavigationListener {
	private DragSortListView lvRate;
//	private Switch switchConversion;
//	private LinearLayout switchLine;
	private CurrentPriceArrayAdapter adapter;
	// for empty view
	private View mEmptyLoadingView = null;
	
	private AdView adView ;
	
	private ExchangeDao exchangeDao;
	private int idx;
	private int pos;
	private static final String SHARED_FILE_NAME = "shared.png";
	
	private DragSortListView.DropListener onDrop = new DragSortListView.DropListener() {
		@Override
		public void drop(int from, int to) {
			TimePrice item = adapter.getItem(from);
			adapter.remove(item);
			adapter.insert(item, to);
			List<String> sortkeys = SortKeeper.readSortkeys(getApplicationContext());
			sortkeys.remove(from);
			sortkeys.add(to, item.getName());
			SortKeeper.keepSortkeys(getApplicationContext(), sortkeys);
		}
	};
	
	public boolean onOptionsItemSelected(MenuItem item) {
		if ("refresh".equals(item.getTitle())) {
			showProgress(true);
			idx = lvRate.getFirstVisiblePosition();
			View vfirst = lvRate.getChildAt(0);
			pos = 0;
			if (vfirst != null) pos = vfirst.getTop();
			showLoadingEmptyView();
			if (priceTask != null) {
				priceTask.cancel(true);
			}
			priceTask = new DownloadTimePriceTask();
			showProgress(true);
			priceTask.execute(this);
			return true;
		}
		
		return true;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setTheme(R.style.Theme_sherlock_light);
		super.onCreate(savedInstanceState);
		setTitle(R.string.title_activity_current_price);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.current_price_activity);
		int bank = SortKeeper.readBank(getApplicationContext());
		if (bank == 0) {
			exchangeDao = new BocExchangeDao();
		} else {
			exchangeDao = new IcbcExchangeDao();
		}
		
        Context context = getSupportActionBar().getThemedContext();
        ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.banks, R.layout.sherlock_spinner_item);
        list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        getSupportActionBar().setListNavigationCallbacks(list, this);
        getSupportActionBar().setSelectedNavigationItem(bank);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
		lvRate = (DragSortListView) this.findViewById(R.id.listView1);
		lvRate.setDropListener(onDrop);
		lvRate.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int position,
					long id) {
				CurrentPriceActivity.this.onItemClick(adapterView, view, position, id);
			}
			
		});
//		switchConversion = (Switch) this.findViewById(R.id.switchConversion);
//		switchConversion.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				//汇率
//				if (switchConversion.isChecked()) {
//					lvRate.setVisibility(View.VISIBLE);
//				} else {
//				//换算
//					lvRate.setVisibility(View.GONE);
//				}
//			}
//			
//		});
//		
//		switchLine = (LinearLayout) this.findViewById(R.id.switchline);
		adView = (AdView)this.findViewById(R.id.adView);
	    adView.loadAd(new AdRequest());
	    adView.setAdListener(new AdlistenerTracker(getApplicationContext()));
	    MarketService ms = new MarketService(this);
		ms.level(MarketService.MINOR).checkVersion();
	}
	

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (adView != null) {
			adView.destroy();
			adView = null;
		}
		lvRate = null;
		adapter = null;
	}

	// show loading view when init and loading data from network
	protected void showLoadingEmptyView() {
		if (mEmptyLoadingView == null) {
			mEmptyLoadingView = EmptyViewUtils.createLoadingView(this);
		}
		if (adapter != null) {
			adapter.clear();
			adapter.notifyDataSetChanged();
		}
		((ViewGroup) lvRate.getParent()).removeView(mEmptyLoadingView);
		((ViewGroup) lvRate.getParent()).addView(mEmptyLoadingView);
		lvRate.setEmptyView(mEmptyLoadingView);
//		switchLine.setVisibility(View.GONE);
	}

	private class DownloadTimePriceTask extends
			AsyncTask<FragmentActivity, Void, List<TimePrice>> {
		private FragmentActivity context;
		@Override
		protected List<TimePrice> doInBackground(FragmentActivity... context) {
			this.context = context[0];
			List<TimePrice> timePrices = new ArrayList<TimePrice>();
			if (NetWorkUtil.isOnline(getApplicationContext())) {
				timePrices = exchangeDao.findByCurrencyNow(getApplicationContext());
			}
			return timePrices;
		}

		@Override
		protected void onPostExecute(List<TimePrice> timeprices) {
			if (!NetWorkUtil.isOnline(getApplicationContext())) {
				Toast.makeText(CurrentPriceActivity.this, R.string.non_connected, Toast.LENGTH_SHORT).show();
			}
			if (isCancelled()) {
				return;
			}
//			if (timeprices != null && timeprices.size() != 0) {
//				switchLine.setVisibility(View.VISIBLE);
//			} else {
//				switchLine.setVisibility(View.GONE);
//			}
			adapter = new CurrentPriceArrayAdapter(context,
					R.layout.current_timeprice_item, timeprices);
			lvRate.setAdapter(adapter);
			adapter.notifyDataSetChanged();
			if (mEmptyLoadingView != null) {
				mEmptyLoadingView.setVisibility(View.INVISIBLE);
			}
			if (idx != 0 && pos != 0) {
				//Restore the position
				lvRate.setSelectionFromTop(idx, pos);
			}
			showProgress(false);
		}
	}
	
    protected void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        Intent intent = new Intent(this, HistoryActivity.class);
        intent.putExtra("currencyId",CurrencyConverter.getIdByName(this, adapter.getItem(position).getName(), SortKeeper.readBank(getApplicationContext())));
        startActivity(intent);
    }

	private DownloadTimePriceTask priceTask;
	
	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		if (itemPosition == 0) {
			exchangeDao = new BocExchangeDao();
		} else {
			exchangeDao = new IcbcExchangeDao();
		}
		SortKeeper.keepBank(getApplicationContext(), itemPosition);
		idx = lvRate.getFirstVisiblePosition();
		View vfirst = lvRate.getChildAt(0);
		pos = 0;
		if (vfirst != null) pos = vfirst.getTop();
		showLoadingEmptyView();
		if (priceTask != null) {
			priceTask.cancel(true);
		}
		priceTask = new DownloadTimePriceTask();
		showProgress(true);
		priceTask.execute(this);
		return true;
	}
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		if (!progressEnabled) {
			menu.add("refresh").setIcon(R.drawable.ic_action_refresh)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		}
		
        // Inflate your menu.
        getSupportMenuInflater().inflate(R.menu.share_action_provider, menu);

        // Set file with share history to the provider and set the share intent.
        MenuItem actionItem = menu.findItem(R.id.menu_item_share_action_provider_action_bar);
        ShareActionProvider actionProvider = (ShareActionProvider) actionItem.getActionProvider();
        actionProvider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener() {
			
			@Override
			public boolean onShareTargetSelected(ShareActionProvider source,
					Intent intent) {
				if (!NetWorkUtil.isOnline(getApplicationContext())) {
					return false;
				}
				Bitmap image = Bitmap.createBitmap(lvRate.getWidth(), lvRate.getHeight(), Bitmap.Config.RGB_565);
				lvRate.draw(new Canvas(image));
				
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] data;
            	image.compress(CompressFormat.PNG, 75, bos);
            	data = bos.toByteArray();
            	
            	FileOutputStream os = null;
				try {
					os = openFileOutput(SHARED_FILE_NAME,
					        Context.MODE_WORLD_READABLE);
					os.write(data, 0, data.length);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
		            try {
		            	os.close();
		            } catch (IOException ioe) {
		               /* ignore */
		            }
		            try {
		            	bos.close();
		            } catch (IOException ioe) {
		               /* ignore */
		            }
		        }
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				Uri uri = Uri.fromFile(getFileStreamPath(SHARED_FILE_NAME));
				intent.getExtras().clear();
				intent.putExtra(Intent.EXTRA_STREAM, uri);
				intent.putExtra(Intent.EXTRA_TEXT, "\n" + getResources().getString(R.string.sharewith_tiles));
				getApplicationContext().startActivity(intent);
				return true;
			}
		});
        actionProvider.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
        actionProvider.setShareIntent(createShareIntent());

        return true;
    }

    /**
     * Creates a sharing {@link Intent}.
     *
     * @return The sharing intent.
     */
    private Intent createShareIntent() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        Uri uri = Uri.fromFile(getFileStreamPath("shared.png"));
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        return shareIntent;
    }
    
    private boolean progressEnabled = false;
	private void showProgress(boolean progressEnabled) {
		this.progressEnabled = progressEnabled;
		invalidateOptionsMenu();
		setSupportProgressBarIndeterminateVisibility(progressEnabled);
	}
}
